﻿using System;
using System.Configuration;
using System.Xml;

namespace NDBGen.Configuration
{
    public class NDBGenSection : ConfigurationSection
    {
        public NDBGenSection()
        {
        }

        public NDBGenSection(System.Configuration.Configuration config, String configPath)
        {
            using (var reader = new XmlTextReader(configPath))
            {
                this.DeserializeSection(reader);
                if (config.Sections["ndbgen"] != null) config.Sections.Remove("ndbgen");
                config.Sections.Add("ndbgen", this);
            }
        }

        const String SECTION_NAME = "ndbgen";

        const String PROPNAME_INPUT = "input";
        [ConfigurationProperty(PROPNAME_INPUT, IsRequired = false)]
        public InputElement Input
        {
            get { return (InputElement)this[PROPNAME_INPUT]; }
            set { this[PROPNAME_INPUT] = value; }
        }

        const String PROPNAME_OUTPUT = "output";
        [ConfigurationProperty(PROPNAME_OUTPUT, IsRequired = false)]
        public OutputElement Output
        {
            get { return (OutputElement)this[PROPNAME_OUTPUT]; }
            set { this[PROPNAME_OUTPUT] = value; }
        }

        public static NDBGenSection GetCurrent(String configPath)
        {
            NDBGenSection section;
            if (configPath == null) section = (NDBGenSection)ConfigurationManager.GetSection(SECTION_NAME);
            else
            {
                var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                section = new NDBGenSection(config, configPath);
            }

            if(section == null) throw new ConfigurationErrorsException(String.Format("Could not find a configuration section named {0}", SECTION_NAME));

            return section;
        }
    }
}